package cn.rojao.wx.web.system.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rojao.wx.common.base.BaseController;
import cn.rojao.wx.common.constant.SessionAttr;
import cn.rojao.wx.common.util.MenuUtils;
import cn.rojao.wx.web.system.entity.SysMenu;
import cn.rojao.wx.web.system.entity.SysUser;
import cn.rojao.wx.web.system.service.SysMenuService;
import cn.rojao.wx.web.system.service.SysUserService;
import net.sf.json.JSONObject;

@Controller 
@RequestMapping("/login")
public class LoginController extends BaseController {

	private Logger logger = Logger.getLogger(LoginController.class);
	
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysMenuService sysMenuService;
	
	
	
	/**
	 * 验证用户
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public String checkUser(SysUser user,HttpServletRequest request){
		JSONObject json = new JSONObject();
		
		try {
			
			
			SysUser u = sysUserService.findByUsername(user);
			tryLogin(null,null,true);
			if(u != null){
				
				HttpSession session = request.getSession();
				session.setAttribute(SessionAttr.USER_LOGIN.getValue(), u);
				List<Long> userMenus = sysUserService.findMenuIdByUserId(u.getId());
				List<SysMenu> menuList = sysMenuService.getByParentId(0L);
				session.setAttribute(SessionAttr.USER_MENUS.getValue(), MenuUtils.getMenu(menuList, userMenus));
				
				logger.info("login success");
				json.put("result", "login_success");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
		return json.toString();
	}
	
	
	
	/**
	 * 登录
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String login(){
		return "login/login";
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request){
		
		HttpSession session = request.getSession();
		session.removeAttribute(SessionAttr.USER_LOGIN.getValue());
		session.removeAttribute(SessionAttr.USER_ROLES.getValue());
		session.removeAttribute(SessionAttr.USER_MENUS.getValue());
		
		return "login/login";
	}
	
	
	
	 private boolean tryLogin(String username, String password, Boolean rememberMe)
	    {
	        // get the currently executing user:
	        Subject currentUser = SecurityUtils
	                .getSubject();
	        currentUser.getPrincipal();
	  /*      if (!currentUser.isAuthenticated()) {
	            // collect user principals and credentials in a gui specific manner
	            // such as username/password html form, X509 certificate, OpenID,
	            // etc.
	            // We'll use the username/password example here since it is the most
	            // common.
	            UsernamePasswordToken token = new UsernamePasswordToken(username,
	                    password);
	            // this is all you have to do to support 'remember me' (no config -
	            // built in!):
	            token.setRememberMe(rememberMe);

	            try {
	                currentUser.login(token);
	                System.out.println("User ["
	                        + currentUser.getPrincipal().toString()
	                        + "] authenticated.");

	                // save current username in the session, so we have access to
	                // our User model
	                currentUser.getSession().setAttribute("username", username);
	                return true;
	            } catch (UnknownAccountException uae) {
	                System.out.println("No user found with such username "
	                        + token.getPrincipal());
	            } catch (IncorrectCredentialsException ice) {
	                System.out.println("Password for acount "
	                        + token.getPrincipal()
	                        + " is not valid!");
	            } catch (LockedAccountException lae) {
	                System.out.println("The account for user "
	                        + token.getPrincipal()
	                        + " is blocked.  "
	                        + "Please, contact the administrator to unblock it.");
	            } catch (AuthenticationException ae) {
	                System.out.println("User cannot be authenticated. "
	                        + token.getPrincipal());
	            }
	        } else {
	            return true; // already logged in
	        }*/

	        return false;
	    }
	
}
